package com.littcore.saap.message.biz.impl;

import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import javax.annotation.Resource;
import javax.mail.MessagingException;

import org.slf4j.Logger;

import me.chanjar.weixin.common.exception.WxErrorException;

import com.littcore.common.BeanManager;
import com.littcore.saap.common.service.IEmailService;
import com.littcore.saap.common.service.ITemplateService;
import com.littcore.saap.common.vo.IUserInfo;
import com.littcore.saap.core.module.message.BaseMessage;
import com.littcore.saap.message.biz.IMessageBizService;
import com.littcore.saap.message.dao.UserMessageDao;
import com.littcore.saap.message.dao.UserMessageSubDao;
import com.littcore.saap.message.po.UserMessageSub;
import com.littcore.saap.message.webservice.IMessageWebService;
import com.littcore.saap.system.service.IUserInfoService;
import com.littcore.saas.wechat.service.IWechatCpService;


/**
 * .
 * 
 * <pre><b>描述：</b>
 *    
 * </pre>
 * 
 * <pre><b>修改记录：</b>
 *    
 * </pre>
 * 
 * @author <a href="mailto:littcai@hotmail.com">蔡源</a>
 * @since 2015年10月27日
 * @version 1.0
 */
public class MessageBizServiceImpl implements IMessageBizService, IMessageWebService {
  
  @Resource
  private UserMessageSubDao userMessageSubDao;
  @Resource
  private UserMessageDao userMessageDao;
  @Resource
  private IUserInfoService userInfoService;
  @Resource
  private ITemplateService templateService;
  @Resource
  private IEmailService emailService;
  @Resource
  private IWechatCpService wechatCpService;
  
  private String wechatCpBaseUrl;
  
  /**
   * 统一消息处理.
   * 若发送消息失败，应统一转存并通知给系统管理员，可转人工服务
   */
  public void onMessage(BaseMessage message)
  {
    if(message.getFromBy()==message.getReceiveBy()) //如果发件人跟收件人是一个，不发消息
      return;
    String metaCode = message.getMetaCode();
    
    IUserInfo fromUser = null;
    if(message.getFromBy()>0)
    {
      fromUser = userInfoService.find(message.getFromBy());
    }
    IUserInfo receiveUser = userInfoService.find(message.getReceiveBy());
    //根据消息接收人的订阅设置选择对应通道组织内容并进行发送    
    
    
    
    Locale locale = receiveUser.toLocale();
    String messageName = BeanManager.getMessage("message.module."+message.getModuleCode()+"."+message.getMessageCode(), locale);
    
    Map<String, Object> propMap = new HashMap<String, Object>();
    propMap.put("baseUrl", "http://saas.littcore.com");
    propMap.put("channel", "email");
    propMap.put("fromUser", fromUser);
    propMap.put("receiveUser", receiveUser);
    propMap.put("message", message);
    propMap.put("wechatCpBaseUrl", this.wechatCpBaseUrl);
    
    String content = templateService.genString(metaCode, propMap);
    
    //try
    //{
      //emailService.sendMime(receiveUser.getEmail(), messageName, content, content);
    //} catch (MessagingException e)
   // {
    //  e.printStackTrace();
    //}
    //发送微信通知
    
    try
    {
      propMap = new HashMap<String, Object>();
      propMap.put("baseUrl", "http://saas.littcore.com");
      propMap.put("channel", "wechat");
      propMap.put("fromUser", fromUser);
      propMap.put("receiveUser", receiveUser);
      propMap.put("message", message);
      
      content = templateService.genString(metaCode, propMap);
     
      wechatCpService.sendUserModuleMessage(message.getModuleCode(), content, true, ""+message.getReceiveBy());
      
    } catch (WxErrorException e)
    {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  
  /* (non-Javadoc)
   * @see com.littcore.saap.message.biz.impl.IMessageBizService#sendMessage(com.littcore.saap.core.module.message.BaseMessage)
   */
  @Override
  public void sendMessage(BaseMessage message)
  {
    this.onMessage(message);
  }
  
  /**
   * 注册消息.
   * 
   * 用户可在个人中心选择订阅的消息列表
   */
  public void register()
  {
    
  }
  
  /* (non-Javadoc)
   * @see com.littcore.saap.message.biz.impl.IMessageBizService#subscribe(int, int, java.lang.String, java.lang.String, java.lang.String, java.lang.String[])
   */
  @Override
  public void subscribe(int userId, int tenantId, String domainCode, String moduleCode, String messageCode, String[] channels)
  {
    //String uid = domainCode+"-"+moduleCode+"-"+messageCode+"-"+userId+"-"+tenantId;
    
    UserMessageSub userMessageSub = new UserMessageSub();
    userMessageSub.setTenantId(tenantId);
    userMessageSub.setCreateBy(userId);
    userMessageSub.setCreateDatetime(new Date());
    userMessageSub.setChannels(Arrays.toString(channels));
    userMessageSubDao.save(userMessageSub);
  }
  
  /* (non-Javadoc)
   * @see com.littcore.saap.message.biz.impl.IMessageBizService#unsubscribe(java.lang.String)
   */
  @Override
  public void unsubscribe(int id)
  {
    userMessageSubDao.deleteById(id);
  }

  
  /**
   * @return the wechatCpBaseUrl
   */
  public String getWechatCpBaseUrl()
  {
    return wechatCpBaseUrl;
  }

  
  /**
   * @param wechatCpBaseUrl the wechatCpBaseUrl to set
   */
  public void setWechatCpBaseUrl(String wechatCpBaseUrl)
  {
    this.wechatCpBaseUrl = wechatCpBaseUrl;
  }
  
}
